/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package my.cbr.database;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import jcolibri.test.database.HSQLDBserver;
import jcolibri.util.FileIO;
import org.hsqldb.Server;
import org.hsqldb.util.SqlFile;

/**
 *
 * @author Geir Ole
 */
public class HSQLDBServer {

    static String username = "sa";
    static String password = "";
    static String database = "fishtest";
    static boolean initialized = false;
    private static Server server;

    public static void init()
    {
	if (initialized)
	    return;
        org.apache.commons.logging.LogFactory.getLog(HSQLDBServer.class).info("Creating data base ...");

	server = new Server();
	server.setDatabaseName(0, HSQLDBServer.database);
	server.setDatabasePath(0, "mem:"+HSQLDBServer.database+";sql.enforce_strict_size=true");

	server.setLogWriter(null);
	server.setErrWriter(null);
	server.setSilent(true);
	server.start();

	initialized = true;
	try
	{
	    Class.forName("org.hsqldb.jdbcDriver");

	    PrintStream out = new PrintStream(new ByteArrayOutputStream());
	    Connection conn = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/"+HSQLDBServer.database,
                    HSQLDBServer.username, HSQLDBServer.password);
	    SqlFile file = new SqlFile(new
	    File(FileIO.findFile("cbrv1/"+HSQLDBServer.database+".sql").getFile()),false,new HashMap());
	    file.execute(conn,out,out, true);

	    org.apache.commons.logging.LogFactory.getLog(HSQLDBserver.class).info("Data base generation finished");

	} catch (Exception e)
	{
	    org.apache.commons.logging.LogFactory.getLog(HSQLDBserver.class).error(e);
	}

    }

    /**
     * Shutdown the server
     */
    public static void shutDown()
    {

	if (initialized)
	{
	    server.stop();
	    initialized = false;
	}
    }

    /**
     * Testing method
     */
    public static void main(String[] args)
    {
	HSQLDBServer.init();
	HSQLDBServer.shutDown();
	System.exit(0);

    }

}
